package com.triones.yjj.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.domain.SysUserRole;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.triones.yjj.entity.*;
import com.triones.yjj.entity.bo.*;
import com.triones.yjj.entity.vo.*;
import com.triones.yjj.mapper.*;
import com.triones.yjj.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 客户管理 service 业务实现
 *
 * @Author: triones
 */
@Service
@RequiredArgsConstructor
public class MemberServiceImpl implements MemberService {

    private final MemberMapper memberMapper;

    private final OldMemberMapper oldMemberMapper;

    private final OrderMapper orderMapper;

    private final MemberDistributionRecordMapper memberDistributionRecordMapper;

    private final MemberBrowseMapper memberBrowseMapper;

    private final ShareMapper shareMapper;

    private final MemberBrowseRecordMapper memberBrowseRecordMapper;

    private final ActivityMapper activityMapper;

    private final MemberActivityRelateMapper memberActivityRelateMapper;

    private final MemberWithdrawMapper memberWithdrawMapper;

    private final MemberFundRecordMapper memberFundRecordMapper;

    @Override
    public TableDataInfo<MemberListVO> pageList(MemberListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        params.setUserId(loginUser.getUserId());
        if (params.getDateRange() != null && params.getDateRange().size() > 0) {
            params.setStartTime(params.getDateRange().get(0));
            params.setEndTime(params.getDateRange().get(1));
        }
        Page<MemberListVO> result = memberMapper.pageList(pageQuery.build(), params);
        return TableDataInfo.build(result);
    }

    @Override
    public Boolean setMemberToOldOrNew(Long[] memberIds, Integer type) {
        List<Long> ids = Arrays.asList(memberIds);
        LambdaQueryWrapper<MemberDO> wrapper = Wrappers.lambdaQuery(MemberDO.class);
        wrapper.in(MemberDO::getId, ids);
        List<MemberDO> memberDOList = memberMapper.selectList(wrapper);
        if (memberDOList != null && memberDOList.size() > 0) {
            memberDOList.forEach(t -> {
                t.setNewOfOld(type);
            });
            return memberMapper.updateBatchById(memberDOList);
        }
        return true;
    }

    @Override
    public Boolean uploadMobiles(OldMemberBO bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        if (bo.getMemberMobiles() == null || bo.getMemberMobiles().size() == 0) {
            throw new ServiceException("客户手机号不能为空");
        }
        List<OldMemberDO> memberDOList = new ArrayList<>();
        bo.getMemberMobiles().forEach(item -> {
            LambdaQueryWrapper<OldMemberDO> wrapper = Wrappers.lambdaQuery(OldMemberDO.class);
            wrapper.eq(OldMemberDO::getMemberMobile, item);
            wrapper.eq(OldMemberDO::getDeleted, 0);
            OldMemberDO oldMemberDO = oldMemberMapper.selectOne(wrapper);
            if (oldMemberDO == null) {
                OldMemberDO oldMember = new OldMemberDO();
                oldMember.setUserId(loginUser.getUserId());
                oldMember.setMemberMobile(item);
                memberDOList.add(oldMember);
            }
        });
        if (memberDOList.size() > 0) {
            oldMemberMapper.insertBatch(memberDOList);
        }
        return true;
    }

    @Override
    public TableDataInfo<OldMemberVO> oldMemberMobilePageList(OldMemberParams params, PageQuery pageQuery) {
        LambdaQueryWrapper<OldMemberDO> wrapper = Wrappers.lambdaQuery(OldMemberDO.class);
        wrapper.like(StringUtils.isNotBlank(params.getKeyword()), OldMemberDO::getMemberMobile, params.getKeyword());
        wrapper.eq(OldMemberDO::getDeleted, 0);
        Page<OldMemberVO> result = oldMemberMapper.selectVoPage(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public Boolean delMemberMobiles(Long[] ids) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        List<Long> mobileIds = Arrays.asList(ids);
        return oldMemberMapper.deleteBatchIds(mobileIds) > 0;
    }

    @Override
    public Map dataShowStats(MemberListParams params) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        params.setUserId(loginUser.getUserId());
        if (params.getDateRange() != null && params.getDateRange().size() > 0) {
            params.setStartTime(params.getDateRange().get(0));
            params.setEndTime(params.getDateRange().get(1));
        }
        Map map = new HashMap();
        Long memberTotal = memberMapper.memberTotal(params);
        map.put("memberTotal", Convert.toInt(memberTotal, 0));
        Long newMemberTotal = memberMapper.newMemberTotal(params);
        map.put("newMemberTotal", Convert.toInt(newMemberTotal, 0));
        Long oldMemberTotal = memberMapper.oldMemberTotal(params);
        map.put("oldMemberTotal", Convert.toInt(oldMemberTotal, 0));
        Long excellentTotal = memberMapper.excellentTotal(params);
        map.put("excellentTotal", Convert.toInt(excellentTotal, 0));
        Long orderMemberTotal = memberMapper.orderMemberTotal(params);
        map.put("orderMemberTotal", Convert.toInt(orderMemberTotal, 0));
        Long distributionMemberTotal = memberMapper.distributionMemberTotal(params);
        map.put("distributionMemberTotal", Convert.toInt(distributionMemberTotal, 0));
        LambdaQueryWrapper<OldMemberDO> oldWrapper = Wrappers.lambdaQuery(OldMemberDO.class);
        Long manualUploadOldMemberTotal = oldMemberMapper.selectCount(oldWrapper);
        map.put("manualUploadOldMemberTotal", Convert.toInt(manualUploadOldMemberTotal, 0));
        return map;
    }

    @Override
    public Map memberInfoStats(Long memberId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        Map map = new HashMap();
        LambdaQueryWrapper<OrderDO> orderTotalWrapper = Wrappers.lambdaQuery(OrderDO.class);
        orderTotalWrapper.eq(OrderDO::getMemberId, memberId)
            .eq(OrderDO::getUserId, loginUser.getUserId());
        Long placeOrderNumTotal = orderMapper.selectCount(orderTotalWrapper);
        map.put("placeOrderNumTotal", Convert.toInt(placeOrderNumTotal, 0));
        String realityPayAmountTotal = orderMapper.getRealityPayAmountTotal(memberId, loginUser.getUserId());
        map.put("realityPayAmountTotal", Convert.toBigDecimal(realityPayAmountTotal, BigDecimal.ZERO));
        String refundTotal = orderMapper.getRefundTotal(memberId, loginUser.getUserId());
        map.put("refundTotal", Convert.toBigDecimal(refundTotal, BigDecimal.ZERO));
        List<Map> distributionNumberMap = memberDistributionRecordMapper.getDistributionNumber(memberId, loginUser.getUserId());
        if (distributionNumberMap.size() > 0) {
            for (Map item : distributionNumberMap) {
                if (Convert.toInt(item.get("distribution_grade")) == 1) {
                    map.put("distributionNumberOneTotal", Convert.toInt(item.get("number")));
                    map.put("distributionAmountOneTotal", Convert.toBigDecimal(item.get("kickbackTotal")));
                } else {
                    map.put("distributionNumberOneTotal", 0);
                    map.put("distributionAmountOneTotal", 0);
                }
                if (Convert.toInt(item.get("distribution_grade")) == 2) {
                    map.put("distributionNumberTwoTotal", Convert.toInt(item.get("number")));
                    map.put("distributionAmountTwoTotal", Convert.toBigDecimal(item.get("kickbackTotal")));
                } else {
                    map.put("distributionNumberTwoTotal", 0);
                    map.put("distributionAmountTwoTotal", 0);
                }
            }
        } else {
            map.put("distributionNumberOneTotal", 0);
            map.put("distributionNumberTwoTotal", 0);
            map.put("distributionAmountOneTotal", 0);
            map.put("distributionAmountTwoTotal", 0);
        }
        return map;
    }

    @Override
    public MemberDetailVO selectDetailById(Long memberId) {
        return memberMapper.selectDetailById(memberId);
    }

    @Override
    public Boolean editMember(MemberDO dto) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        return memberMapper.updateById(dto) > 0;
    }

    @Override
    public TableDataInfo<MemberActionListVO> actionPageList(MemberActionParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<MemberBrowseDO> wrapper = Wrappers.query();
        wrapper.eq("a.member_id", params.getMemberId());
        wrapper.eq("a.user_id", loginUser.getUserId());
        wrapper.like(StringUtil.isNotBlank(params.getProductName()), "b.title", params.getProductName());
        wrapper.eq(ObjectUtil.isNotNull(params.getEnrollStatus()) && params.getEnrollStatus() != 0, "a.enroll_status", params.getEnrollStatus());
        if (params.getDateRange() != null && params.getDateRange().size() > 0) {
            wrapper.between(ObjectUtil.isNotNull(params.getEnterTimeType()) && params.getEnterTimeType() == 1,
                "a.create_time", params.getDateRange().get(0), params.getDateRange().get(1));
            wrapper.between(ObjectUtil.isNotNull(params.getEnterTimeType()) && params.getEnterTimeType() == 2,
                "a.lately_access_time", params.getDateRange().get(0), params.getDateRange().get(1));
        }
        wrapper.orderByDesc("a.create_time");
        Page<MemberActionListVO> result = memberBrowseMapper.actionPageList(pageQuery.build(), wrapper);
        if (result.getRecords().size() > 0) {
            result.getRecords().forEach(item -> {
                LambdaQueryWrapper<OrderDO> orderWrapper = Wrappers.lambdaQuery(OrderDO.class);
                orderWrapper.eq(OrderDO::getMemberId, params.getMemberId())
                    .eq(OrderDO::getId, item.getProductId())
                    .eq(OrderDO::getUserId, loginUser.getUserId());
                List<OrderVO> orderVOS = orderMapper.selectVoList(orderWrapper);
                item.setOrderList(orderVOS);
            });
        }
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<MemberDistributionListVO> distributionPageList(MemberDistributionParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<MemberDistributionRecordDO> wrapper = Wrappers.query();
        wrapper.eq("a.member_id", params.getMemberId())
            .eq("a.user_id", loginUser.getUserId())
            .orderByDesc("a.create_time");
        Page<MemberDistributionListVO> result = memberDistributionRecordMapper.distributionPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<MemberOrderListVO> orderPageList(MemberOrderParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<OrderDO> wrapper = Wrappers.query();
        wrapper.eq("a.member_id", params.getMemberId());
        wrapper.eq("a.user_id", loginUser.getUserId());
        wrapper.like(StringUtil.isNotBlank(params.getGoodsName()), "b.welfare_name", params.getGoodsName())
            .or().like(StringUtil.isNotBlank(params.getGoodsName()), "d.goods_name", params.getGoodsName())
            .or().like(StringUtil.isNotBlank(params.getGoodsName()), "d.goods_subtitle", params.getGoodsName());
        wrapper.eq(ObjectUtil.isNotNull(params.getStatus()), "a.status", params.getStatus());
        wrapper.like(ObjectUtil.isNotEmpty(params.getEnrollName()), "a.enroll_name", params.getEnrollName());
        if (params.getEnrollDateRange() != null && params.getEnrollDateRange().size() > 0) {
            wrapper.between("a.create_time", params.getEnrollDateRange().get(0), params.getEnrollDateRange().get(1));
        }
        wrapper.orderByDesc("a.create_time");
        Page<MemberOrderListVO> result = orderMapper.orderPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<ShareListVO> sharePageList(ShareListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<ShareDO> wrapper = Wrappers.query();
        wrapper.like(StringUtil.isNotBlank(params.getWxNickname()), "d.nickname", params.getWxNickname());
        wrapper.like(StringUtil.isNotBlank(params.getRemark()), "b.remark", params.getRemark());
        wrapper.eq(ObjectUtil.isNotNull(params.getEnrollStatus()) && params.getEnrollStatus() != 0, "a.enroll_status", params.getEnrollStatus());
        wrapper.eq(ObjectUtil.isNotNull(params.getProductType()) && params.getProductType() != 0, "a.product_type", params.getProductType());
        wrapper.eq(ObjectUtil.isNotNull(params.getActivityId()), "a.product_id", params.getActivityId());
        wrapper.eq(ObjectUtil.isNotNull(params.getMemberId()), "a.member_id", params.getMemberId());
        wrapper.eq("a.user_id", loginUser.getUserId());
        wrapper.orderByDesc("a.create_time");
        Page<ShareListVO> result = shareMapper.sharePageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public Map shareDataStats(ShareListParams params) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        Map map = new HashMap();
        /**
         * shareNumberTotal 分享次数
         * spreadNumberTotal 传播人数
         * memberBuyNumberTotal 购买人数
         * buyNumberTotal 购买次数
         * payTotalTotal 付款总金额
         */
        LambdaQueryWrapper<ShareDO> shareLqw = Wrappers.lambdaQuery();
        shareLqw.eq(ShareDO::getUserId,loginUser.getUserId())
            .eq(ObjectUtil.isNotNull(params.getActivityId()),ShareDO::getProductId,params.getActivityId());
        List<ShareDO> shareDOList = shareMapper.selectList(shareLqw);
        if (shareDOList != null && shareDOList.size() > 0) {
            map.put("shareNumberTotal",shareDOList.stream().mapToInt(ShareDO::getShareNumber).sum());
            map.put("spreadNumberTotal",shareDOList.stream().mapToInt(ShareDO::getSpreadNumber).sum());
        } else {
            map.put("shareNumberTotal",0);
            map.put("spreadNumberTotal",0);
            map.put("memberBuyNumberTotal",0);
        }

        LambdaQueryWrapper<OrderDO> orderLqw = Wrappers.lambdaQuery();
        orderLqw.eq(OrderDO::getUserId,loginUser.getUserId()).in(OrderDO::getStatus,2,5)
            .eq(ObjectUtil.isNotNull(params.getActivityId()),OrderDO::getActivityId,params.getActivityId());
        List<OrderDO> orderDOList = orderMapper.selectList(orderLqw);
        if (orderDOList != null && orderDOList.size() > 0) {
            map.put("buyNumberTotal",orderDOList.size());
            map.put("payTotalTotal",orderDOList.stream().map(OrderDO::getRealityPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        } else {
            map.put("buyNumberTotal",0);
            map.put("payTotalTotal",0);
        }
        map.put("memberBuyNumberTotal",shareMapper.countMemberBuyNumberTotal(loginUser.getUserId(),params.getActivityId()));
        return map;
    }

    @Override
    public TableDataInfo<PotentialListVO> potentialPageList(PotentialListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<MemberBrowseDO> wrapper = Wrappers.query();
        wrapper.eq("a.user_id", loginUser.getUserId());
        wrapper.eq("a.enroll_status", 2);
        wrapper.like(ObjectUtil.isNotEmpty(params.getWxNickname()), "e.nickname", params.getWxNickname());
        wrapper.eq(ObjectUtil.isNotEmpty(params.getMemberType()) && params.getMemberType() != 0, "a.member_status", params.getMemberType());
        if (params.getBrowseSchedule() != null) {
            String[] split = params.getBrowseSchedule().split(",");
            wrapper.between("a.browse_ratio", split[0], split[1]);
        }
        if (params.getDateRange() != null && params.getDateRange().size() > 0) {
            wrapper.between("a.lately_access_time", params.getDateRange().get(0), params.getDateRange().get(1));
        }
        wrapper.like(ObjectUtil.isNotEmpty(params.getRemark()), "c.remark", params.getRemark());
        wrapper.eq(ObjectUtil.isNotNull(params.getProductType()), "a.product_type", params.getProductType());
        wrapper.eq(ObjectUtil.isNotNull(params.getActivityId()), "a.product_id", params.getActivityId());
        wrapper.isNotNull(ObjectUtil.isNotNull(params.getIsEnrollInfo()) && params.getIsEnrollInfo() == 1, "c.name");
        wrapper.isNotNull(ObjectUtil.isNotNull(params.getIsEnrollInfo()) && params.getIsEnrollInfo() == 1, "c.mobile");
        wrapper.isNull(ObjectUtil.isNotNull(params.getIsEnrollInfo()) && params.getIsEnrollInfo() == 2, "c.name");
        wrapper.isNull(ObjectUtil.isNotNull(params.getIsEnrollInfo()) && params.getIsEnrollInfo() == 2, "c.mobile");
        Page<PotentialListVO> result = memberBrowseMapper.potentialPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<MemberBrowseRecordVO> browseRecordPageList(BrowseRecordListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        LambdaQueryWrapper<MemberBrowseRecordDO> lqw = Wrappers.lambdaQuery();
        lqw.eq(MemberBrowseRecordDO::getUserId, loginUser.getUserId())
            .eq(MemberBrowseRecordDO::getBrowseId, params.getBrowseId())
            .orderByAsc(MemberBrowseRecordDO::getEntryTime);
        Page<MemberBrowseRecordVO> result = memberBrowseRecordMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public Map browseStats() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        Map map = new HashMap();
        /**
         * 今日新增潜在用户
         */
        Long todayAddMemberNumber = memberBrowseMapper.selectCount(new LambdaQueryWrapper<MemberBrowseDO>()
            .eq(MemberBrowseDO::getUserId, loginUser.getUserId())
            .between(MemberBrowseDO::getCreateTime, DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()))
            .ne(MemberBrowseDO::getEnrollStatus, 1));
        map.put("todayAddMemberNumber", Convert.toInt(todayAddMemberNumber, 0));
        /**
         * 今日新增手机客户
         */
        Long todayAddMemberMobileNumber = memberBrowseMapper.selectCount(new LambdaQueryWrapper<MemberBrowseDO>()
            .eq(MemberBrowseDO::getUserId, loginUser.getUserId())
            .between(MemberBrowseDO::getCreateTime, DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()))
            .ne(MemberBrowseDO::getEnrollStatus, 1)
            .isNotNull(MemberBrowseDO::getRemainMobile));
        map.put("todayAddMemberMobileNumber", Convert.toInt(todayAddMemberMobileNumber, 0));
        /**
         * 总的潜在客户
         */
        Long memberNumberTotal = memberBrowseMapper.selectCount(new LambdaQueryWrapper<MemberBrowseDO>()
            .eq(MemberBrowseDO::getUserId, loginUser.getUserId())
            .ne(MemberBrowseDO::getEnrollStatus, 1));
        map.put("memberNumberTotal", Convert.toInt(memberNumberTotal, 0));
        /**
         * 总留手机号客户
         */
        Long memberMobileNumberTotal = memberBrowseMapper.selectCount(new LambdaQueryWrapper<MemberBrowseDO>()
            .eq(MemberBrowseDO::getUserId, loginUser.getUserId())
            .ne(MemberBrowseDO::getEnrollStatus, 1)
            .isNotNull(MemberBrowseDO::getRemainMobile));
        map.put("memberMobileNumberTotal", Convert.toInt(memberMobileNumberTotal, 0));
        return map;
    }

    @Override
    public Map browseRecordStats(Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        Map map = new HashMap();
        MemberBrowseDO memberBrowseDO = memberBrowseMapper.selectById(id);
        if (memberBrowseDO == null) {
            throw new SecurityException("没有查询到该潜在用户");
        }
        LambdaQueryWrapper<MemberBrowseRecordDO> shareWrapper = Wrappers.lambdaQuery(MemberBrowseRecordDO.class);
        shareWrapper.eq(MemberBrowseRecordDO::getBrowseId, id)
            .eq(MemberBrowseRecordDO::getMemberId, memberBrowseDO.getMemberId()).eq(MemberBrowseRecordDO::getBrowseType, "share");
        Long shareNumberTotal = memberBrowseRecordMapper.selectCount(shareWrapper);
        map.put("shareNumber", Convert.toInt(shareNumberTotal, 0));
        /**
         * 统计分享次数
         */
        return map;
    }

    public void uploadLatelyActivity(Long memberId, Long activityId) {
        MemberDO memberDO = memberMapper.selectById(memberId);
        if (ObjectUtil.isEmpty(memberDO)) {
            throw new ServiceException("客户不存在!");
        }
        UpdateWrapper<MemberDO> wrapper = new UpdateWrapper<>();
        wrapper.set("lately_activity_id", activityId);
        wrapper.eq("id", memberDO.getId());
        memberMapper.update(memberDO, wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public void applyWithdraw(Long memberId, Double amount, String source) {
        LambdaQueryWrapper<MemberDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(MemberDO::getId, memberId);
        queryWrapper.last(" for update");
        MemberDO memberDO = memberMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(memberDO)) {
            throw new ServiceException("客户不存在!");
        }
        if (memberDO.getWalletAmount().doubleValue() < amount) {
            throw new ServiceException("余额不足!");
        }
        //增加提现申请记录
        MemberWithdrawDO withdrawDO = new MemberWithdrawDO();
        withdrawDO.setMemberId(memberDO.getId());
        withdrawDO.setMemberWxUserId(memberDO.getWxUserId());
        withdrawDO.setAmount(new BigDecimal(amount));
        withdrawDO.setState(1);//状态1申请2审核打款0驳回申请
        memberWithdrawMapper.insert(withdrawDO);
        //增加资金明细
        MemberFundRecordDO memberFundRecordDO = new MemberFundRecordDO();
        memberFundRecordDO.setMemberId(memberDO.getId());
        memberFundRecordDO.setMemberWxUserId(memberDO.getWxUserId());
        memberFundRecordDO.setAmount(new BigDecimal(amount));
        memberFundRecordDO.setType(2);//类型1收入2支出
        memberFundRecordDO.setSource(2);//来源：1佣金2提现3其它
        memberFundRecordDO.setSourceId(withdrawDO.getId());
        memberFundRecordMapper.insert(memberFundRecordDO);
        //修改余额
        UpdateChainWrapper<MemberDO> wrapperOrder = new UpdateChainWrapper<>(memberMapper);
        wrapperOrder.setSql(" wallet_amount=wallet_amount-" + amount);
        wrapperOrder.eq("id", memberId);
        wrapperOrder.update();
    }

}
